package com.cup.common;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.cglib.beans.BeanCopier;

public class BeanCopyUtils {

	private final static Map<String, BeanCopier> CACHE = new ConcurrentHashMap<String, BeanCopier>();

	public static<T> void copy(Object source, T target) {
		if (null == source || null == target) {
			return;
		}
		Class<?> srcClass = source.getClass();
		Class<?> targetClass = target.getClass();
		String cacheKey = getCacheKey(srcClass, targetClass);
		BeanCopier copier = null;
		if (CACHE.containsKey(cacheKey)) {
			copier = CACHE.get(cacheKey);
		} else {
			copier = BeanCopier.create(srcClass, targetClass, false);
			CACHE.putIfAbsent(cacheKey, copier);
		}
		copier.copy(source, target, null);
	}

	private static String getCacheKey(Class<?> srcClass, Class<?> targetClass) {
		return String.format("%s:%s", srcClass.getName(), targetClass.getName());
	}

}
